#pragma once

#include <string>
#include "InetAddr.hpp"
#include "Log.hpp"
#include <list>
#include <memory>
#include <signal.h>

using namespace MyLogModule;
class UserInterface
{
public:
    virtual ~UserInterface() = default;
    virtual void sendTo(int socket,const std::string &message) = 0;
    virtual bool operator==(InetAddr& id) = 0;
};

class User : public UserInterface
{
public:
    User(InetAddr id)
        :_id(id)
    {}

    ~User()
    {}

    virtual void sendTo(int socket,const std::string &message) override
    {
        LOG(DEBUG)  << " send message to" << _id.getIdInfo() <<" info:"<< message;
        ::sendto(socket,message.c_str(),message.size(),0,_id.Getaddr(),_id.Getlen());
    }

    bool operator==(InetAddr& id) override
    {
        return _id == id;
    }

private:
    InetAddr _id;   //唯一标识user
};

class UserManager
{
public:
    UserManager()
    {
    }

    void AddUesr(InetAddr id)
    {
        LockGuard lockguard(_mutex);
        //添加用户
        //1. 判断用户是否存在
        for(auto& user : _onlineUser)
        {
            if(*user == id)
            {
                LOG(ERROR) << "用户 " << id.getIdInfo() << "已经存在，添加失败"; 
                return;
            }
        }
        LOG(ERROR) << "用户 " << id.getIdInfo() << "添加成功"; 
        _onlineUser.push_back(std::make_shared<User>(id));
    }

    void DeleteUserr(InetAddr id)
    {
        auto pos = std::remove_if(_onlineUser.begin(),_onlineUser.end(),[&id](std::shared_ptr<UserInterface> user){
            return *user == id;
        });
        _onlineUser.erase(pos,_onlineUser.end());
    }

    //将消息广播给所有在线用户
    void Router(int socket,std::string message)
    {
        LockGuard lockguard(_mutex);
        for(auto& user : _onlineUser)
        {
            //各用户调用自己的sendTo方法，将消息发送给自己
            user->sendTo(socket,message);
        }
    }
    ~UserManager()
    {
    }
private:
    std::list<shared_ptr<UserInterface>> _onlineUser;   //管理在线用户
    Mutex _mutex;
};
